﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SoccerEvaluator.Common;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;
using SoccerEvaluator.WebSite.App_Code;
using Facebook;

namespace SoccerEvaluator.WebSite
{
    /// <summary>
    /// 
    /// </summary>
    public partial class MatchUpload : System.Web.UI.Page
    {
        /// <summary>
        /// 
        /// </summary>
        private int _projectId
        {
            get { return (int)Session["projectId"]; }
            set { Session["projectId"] = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        private SystemUserInfo SystemUser
        {
            get
            {
                if (Session["user"] != null)
                {
                    SystemUserInfo u = (SystemUserInfo)Session["user"];

                    return u;
                }
                else return null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.txtName.Text = GetFaceBookName();

                try
                {

                    SoccerEvaluatorModelContainer context = new SoccerEvaluatorModelContainer();

                    TemplateInfo projectInfo = ObjectFactory.ToTemplateInfo(context.Templates.FirstOrDefault(c => c.Id == _projectId));

                    if (projectInfo.ProjectMode == (int)ProjectMode.Read)
                    {
                        int totalRows = projectInfo.Scores.Count;
                        string folder = projectInfo.Logo;

                        this.lstScores.DataSource = projectInfo.Scores;
                        this.lstScores.DataBind();
                    }
                    else
                    {
                        Response.Redirect("MatchList.aspx?message=block");
                    }
                }
                catch (Exception)
                {
                    Response.Redirect("MatchList.aspx");
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private string GetFaceBookName()
        {
            string userName = "";
            try
            {
                var accessToken = Session["AccessToken"].ToString();
                var client = new FacebookClient(accessToken);
                dynamic result = client.Get("me", new { fields = "name,id" });
                string name = result.name;
                string id = result.id;

                userName = name;

            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }

            return userName;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdSave_Click(object sender, EventArgs e)
        {
            //bool validCode = ValidateAccessCode(this.txtAccessCode.Text);

            bool validCode = true;

            if (validCode)
            {
                try
                {
                    if (this.txtName.Text.Length > 0)
                    {


                        SoccerEvaluatorModelContainer context = new SoccerEvaluatorModelContainer();

                        Template templateDB = context.Templates.FirstOrDefault(c => c.Id == _projectId);

                        SystemUser userDB = context.SystemUsers.FirstOrDefault(u => u.UserName == this.txtName.Text);

                        int userId = userDB.Id;

                        bool userHaveScores = context.UserScores.Count(c => c.SystemUserId == userId & c.TemplateId == _projectId) > 0;

                        //Si el usuario no ha llenado la polla
                        if (!userHaveScores)
                        {

                            foreach (TemplateScoreInfo t in this.GetScores())
                            {
                                UserScore item = new UserScore();
                                item.Date = t.Date;
                                item.Index = t.Index;
                                item.LocalGoals = t.LocalGoals;
                                item.VisitorGoals = t.VisitorGoals;
                                item.TemplateId = _projectId;
                                item.SystemUserId = userId;
                                context.UserScores.Add(item);
                            }

                            if (context.SaveChanges() > 0)
                            {
                                Response.Redirect("GroupList.aspx?message=SuccessSaving");
                            }
                            else
                            {
                                ShowMessage(Resources.Resource.ErrorSavingMatch);
                            }
                        }
                        else
                        {
                            ShowMessage(Resources.Resource.FileExist);
                        }
                    }
                    else
                    {
                        ShowMessage(Resources.Resource.NeedUser);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.Message);

                    ShowMessage(Resources.Resource.GeneralError);

                }
            }
            else
            {
                ShowMessage(Resources.Resource.InvalidAccessCode);
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resourceMessage"></param>
        private void ShowMessage(string resourceMessage)
        {
            string script = string.Format("alert('{0}');", resourceMessage);

            ClientScript.RegisterStartupScript(typeof(string), "resourceMessage", script, true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private bool ValidateAccessCode(string code)
        {
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private List<TemplateScoreInfo> GetScores()
        {
            List<TemplateScoreInfo> list = new List<TemplateScoreInfo>();

            foreach (RepeaterItem item in lstScores.Items)
            {
                TemplateScoreInfo s = new TemplateScoreInfo();

                TextBox txtLocalGoals = (TextBox)item.FindControl("txtLocalGoals");
                TextBox txtVisitorGoals = (TextBox)item.FindControl("txtVisitorGoals");
                Label lblDate = (Label)item.FindControl("lblDate");
                Label lblLocation = (Label)item.FindControl("lblLocation");
                Label lblLocal = (Label)item.FindControl("lblLocal");
                Label lblVisitor = (Label)item.FindControl("lblVisitor");
                Label lblIndex = (Label)item.FindControl("lblIndex");

                s.Index = int.Parse(lblIndex.Text);
                s.Date = DateTime.Parse(lblDate.Text);
                s.Location = lblLocation.Text;
                s.Local = lblLocal.Text;
                s.Visitor = lblVisitor.Text;
                s.LocalGoals = int.Parse(txtLocalGoals.Text);
                s.VisitorGoals = int.Parse(txtVisitorGoals.Text);

                list.Add(s);
            }

            return list;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("MatchList.aspx?ID={0}", _projectId));
        }
    }
}